package main

import (
    "bytes"
    "fmt"
	"io"
	"io/ioutil"
	"os/exec"
)

//单命令处理
func main() {
	//创建命令
	cmd0 := exec.Command("echo", "-n", "helloworld!")
	//创建输出管道
	stdout0, err := cmd0.StdoutPipe()
	if err != nil {
		fmt.Printf("Error:Can not obtain the stdout pipe for command No.0:%s\n", err)
		return
	}
	//创建错误输出管道
	stderr0, err := cmd0.StderrPipe()
	if err != nil {
		fmt.Println("StderrPipe: ", err.Error())
		return
	}
	//开始执行
	if err := cmd0.Start(); err != nil {
		fmt.Printf("Error:The command No.0 can not be startup:%s\n", err)
		return
	}
	//读取错误
	bytesErr, err := ioutil.ReadAll(stderr0)

	if err != nil {
		fmt.Println("ReadAll stderr: ", err.Error())
		return
	}
	if len(bytesErr) != 0 {
		fmt.Printf("stderr is not nil: %s", bytesErr)
		return
	}
	//下面为读取输出
	var outputBuf0 bytes.Buffer
	for {
		tempOutput := make([]byte, 5)
		n, err := stdout0.Read(tempOutput)
		if err != nil {
			if err == io.EOF {
				break
			} else {
				fmt.Printf("Error:Can not read data from the pipe:%s\n", err)
				return
			}
		}
		if n > 0 {
			outputBuf0.Write(tempOutput[0:n])
		}
	}

	fmt.Println(string(outputBuf0.String()))

}